package com.example.coreshopapp.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.coreshopapp.R;
import com.example.coreshopapp.adapter.ShopCartBottomAdapter;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.utils.OrderingUtils;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import java.math.BigDecimal;
import java.util.List;

import bean.OrderItemBean;
import dao.DaoSession;
import dao.OrderItemBeanDao;

public class BottomShopCartFragment extends BottomSheetDialogFragment {
    private OrderItemBeanDao orderItemBeanDao;
    private List<OrderItemBean> cartList;
    private ShopCartBottomAdapter shopCartBottomAdapter;
    private RecyclerView bottomShopCartRv;
    private TextView allPriceTv;
    private LinearLayout clearItemBtn;
    //    private double allPrice = 0.00;
    private BigDecimal allPrice = new BigDecimal("0.00");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bottom_shop_cart, container, false);
        allPriceTv = view.findViewById(R.id.all_price_tv);
        clearItemBtn = view.findViewById(R.id.clear_item_btn);
        DaoSession daoSession = BaseApplication.getInstance().getDaoSession(inflater.getContext());
        orderItemBeanDao = daoSession.getOrderItemBeanDao();

        allPrice = allPrice.subtract(allPrice);
        allPriceTv.setText(allPriceTv + "");

        // 拿到传递过来的参数
        if (getArguments() != null) {
            String str = getArguments().getString("cartList", "");
            cartList = JSONObject.parseArray(str, OrderItemBean.class);
            cartList.forEach(item -> {
                allPrice = allPrice.add(BigDecimal.valueOf(OrderingUtils.toFixed((item.getPromotionPrice() > 0? item.getPromotionPrice():item.getPrice()) * item.getNums())));
            });
            allPriceTv.setText(allPrice + "");
        }

        bottomShopCartRv = view.findViewById(R.id.bottom_shop_cart_rv);
        shopCartBottomAdapter = new ShopCartBottomAdapter(cartList);
        bottomShopCartRv.setAdapter(shopCartBottomAdapter);
        shopCartBottomAdapter.onAddItemClickListener((item, i) -> {
            // 添加数量，在这修改数据传到首页更新数据库
            OrderItemBean load = orderItemBeanDao.load(item.getId());
            int num = load.getNums() + 1;
            load.setNums(num);
            double price = OrderingUtils.toFixed(load.getNums() * (load.getPromotionPrice() > 0? load.getPromotionPrice():load.getPrice()));
            load.setAmount(price);
            orderItemBeanDao.update(load);
            cartList.get(i).setNums(num);
            cartList.get(i).setAmount(price);
            update(cartList);
            if (setOnAddClickListener != null) {
                setOnAddClickListener.onAddClick(cartList);
            }
        });
        shopCartBottomAdapter.onMinusItemClickListener((item, i) -> {
            // 减少，在这修改数据传到首页更新数据库
            if (cartList.get(i).getNums() == 1) {
                cartList.remove(i);
                orderItemBeanDao.deleteByKey(item.getId());
            } else {
                OrderItemBean load = orderItemBeanDao.load(item.getId());
                int num = cartList.get(i).getNums() - 1;
                double price = OrderingUtils.toFixed(load.getAmount() - (load.getPromotionPrice() > 0? load.getPromotionPrice():load.getPrice()));
                load.setNums(num);
                load.setAmount(price);
                orderItemBeanDao.update(load);
                cartList.get(i).setNums(num);
                cartList.get(i).setAmount(price);
            }
            update(cartList);
            if (setOnMinusClickListener != null) {
                setOnMinusClickListener.onMinusClick(cartList);
            }
        });
        // num点击事件
        shopCartBottomAdapter.setOnItemNumClickListener(orderItem -> {
            if (setOnNumClickListener != null) {
                setOnNumClickListener.onNumClick(orderItem);
            }
        });
        // num 删除事件
        shopCartBottomAdapter.setOperationBtnItemClickListener((orderItem, i) -> {
            new AlertDialog.Builder(getActivity())
                    .setTitle("温馨提示")
                    .setMessage("确认删除该商品吗")
                    .setPositiveButton("确定", (dialogInterface, i1) -> {
                        cartList.remove(i);
                        orderItemBeanDao.deleteByKey(orderItem.getId());
                        update(cartList);
                        if (setOnDeleteClickListener != null) {
                            setOnDeleteClickListener.onDeleteClick(cartList);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();

        });
        click();
        return view;
    }

    public void update(List<OrderItemBean> list) {
        cartList = list;
        shopCartBottomAdapter.update(cartList);
        allPrice = allPrice.subtract(allPrice);
        cartList.forEach(item -> {
            allPrice = allPrice.add(BigDecimal.valueOf(item.getAmount()));
        });
        allPriceTv.setText(allPrice + "");
    }

    private void click() {
        // 删除事件
        clearItemBtn.setOnClickListener(view -> {
            if (setOnClearClickListener != null) {
                setOnClearClickListener.onClearClick();
            }
        });
    }

    public interface SetOnClearClickListener {
        void onClearClick();
    }

    private SetOnClearClickListener setOnClearClickListener;

    public void setClearClick(SetOnClearClickListener newClick) {
        setOnClearClickListener = newClick;
    }


    // 添加
    public interface SetOnAddClickListener {
        void onAddClick(List<OrderItemBean> list); // 需要参数
    }

    private SetOnAddClickListener setOnAddClickListener;

    public void setAddClick(SetOnAddClickListener newClick) {
        setOnAddClickListener = newClick;
    }

    // 减少
    public interface SetOnMinusClickListener {
        void onMinusClick(List<OrderItemBean> list); // 需要参数
    }

    private SetOnMinusClickListener setOnMinusClickListener;

    public void setMinusClick(SetOnMinusClickListener newClick) {
        setOnMinusClickListener = newClick;
    }


    public interface SetOnNumClickListener {
        void onNumClick(OrderItemBean orderItem); // 需要参数
    }

    private SetOnNumClickListener setOnNumClickListener;

    public void setNumClick(SetOnNumClickListener newClick) {
        setOnNumClickListener = newClick;
    }


    public interface SetOnDeleteClickListener {
        void onDeleteClick(List<OrderItemBean> list); // 需要参数
    }

    private SetOnDeleteClickListener setOnDeleteClickListener;

    public void setOnDelete(SetOnDeleteClickListener newClick) {
        setOnDeleteClickListener = newClick;
    }

}